package com.example.demo.test.lecture.test;

import groovy.util.logging.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Random;

@Slf4j
@Component
public class Task {
    private static Logger logger = LoggerFactory.getLogger(Task.class);
    public static Random random = new Random();

    @Async("newAsyncExecutor")
    public void doTaskOne() throws Exception {
        long start = System.currentTimeMillis();
        logger.info("开始做任务一，时间：" + timeFormater(start));
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        logger.info("完成任务一，耗时：" + (end - start) + "毫秒");
    }

    @Async("newAsyncExecutor")
    public void doTaskTwo() throws Exception {
        long start = System.currentTimeMillis();
        logger.info("开始做任务二，时间：" + timeFormater(start));
        Thread.sleep(random.nextInt(10000));
        long end = System.currentTimeMillis();
        logger.info("完成任务二，耗时：" + (end - start) + "毫秒");
    }

    @Async("newAsyncExecutor")
    public void doTaskThree() throws Exception {
        long start = System.currentTimeMillis();
        logger.info("开始做任务三，时间：" + timeFormater(start));

        Thread.sleep(random.nextInt(10000));

        long end = System.currentTimeMillis();
        logger.info("完成任务三，" + timeFormater(end) + "耗时：" + (end - start) + "毫秒");

    }

    public String timeFormater(long timestamp) {
        LocalDateTime localDateTime = LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        return localDateTime.format(dateTimeFormatter);
    }
}
